# -- coding: utf-8 --
import pymongo


class MongoDB:
    url = 'mongodb://127.0.0.1:27017/'
    #url = 'mongodb://118.25.237.31:27017/'
    mongo_client = None
    mongo_db = None

    def __init__(self, db_name):
        try:
            self.mongo_client = pymongo.MongoClient(self.url)
            if self.mongo_client[db_name].authenticate("root", "sa"):
                self.mongo_db = self.mongo_client[db_name]
        except Exception as e:
            print(e)

    def __del__(self):
        self.mongo_client.close()

    # TODO 向集合插入一条数据
    def insert_one(self, col, doc):
        if col is None or col == '':
            print("集合名未指定！")
            return None
        elif doc is None or doc == '':
            print("文档为空！")
            return None
        else:
            try:
                return self.mongo_db[col].insert_one(doc).inserted_id
            except Exception as e:
                print(e)

    # TODO 向集合中插入多条数据
    def insert_many(self, col, docs):
        if col is None or col == '':
            print("集合名未指定！")
        elif docs is None or docs == '' or len(docs) == 0:
            print("文档列表为空！")
        else:
            try:
                return self.mongo_db[col].insert_many(docs).inserted_ids
            except Exception as e:
                print(e)
        return None

    # TODO 查找一个文档
    def find_one(self, col, **kwargs):
        if col is None or col == '':
            print("集合名未指定！")
        elif col not in self.mongo_db.collection_names():
            print("%s中不存在%s！" % (self.mongo_db.name, col))
        else:
            try:
                return self.mongo_db[col].find_one(kwargs)
            except Exception as e:
                print(e)
        return None

    # TODO 查找多个文档
    def find_many(self, col, **kwargs):
        if col is None or col == '':
            print("集合名未指定！")
        elif col not in self.mongo_db.collection_names():
            print("%s中不存在%s！" % (self.mongo_db.name, col))
        else:
            try:
                return self.mongo_db[col].find(kwargs)
            except Exception as e:
                print(e)
        return None

    # TODO 查找指定个数个文档
    def find_many_limit(self, col, limit=1, **kwargs):
        if col is None or col == '':
            print("集合名未指定！")
        elif col not in self.mongo_db.collection_names():
            print("%s中不存在%s！" % (self.mongo_db.name, col))
        else:
            try:
                return self.mongo_db[col].find(kwargs).limie(limit)
            except Exception as e:
                print(e)
        return None
